package xiuXianba

import (
	"fmt"
	"github.com/imroc/req/v3"
	"log"
	"sync"
	"xiuxian_help_tool/backend/utils/sdk"
)

var (
	once              sync.Once
	XiaLouPlatformCli *XiuXianClient
)

func init() {
	once.Do(func() {
		XiaLouPlatformCli = NewXiaLouPlatformClient()
	})
}

// XiuXianClient is the go client for GitHub API.
type XiuXianClient struct {
	*req.Client
	isLogged bool
}

// NewXiaLouPlatformClient create a GitHub client.
func NewXiaLouPlatformClient() *XiuXianClient {
	c := req.C().
		SetCommonHeader("Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6MCwiVWlkIjoxNzY2NTMzMjI0NywiSWF0IjoxNzIyODI0NDgzLCJFeHAiOjE3MjI5MTA4ODN9.IiAWmsUVJPlnLNir7qLKIVeMwxvvx5rvD9SDy23hGSo").
		SetCommonHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5410.0 Safari/537.36").
		SetCommonHeader("Content-Type", "application/json").
		SetCommonHeader("Accept", "*/*").
		SetCommonHeader("Host", "test.backend.xiuxian.xialoukeji.com").
		SetCommonHeader("Connection", "keep-alive").
		SetBaseURL("https://test.xiuxian.xialoukeji.com").
		// 为每个请求在请求级别开启 dump，将内容 dump 到内存中（不打印到 stdout），
		// 我们只在发生意外异常时才能记录 dump 内容，有助于排查生产中的问题。
		EnableDumpEachRequest().
		// Unmarshal all GitHub error response into struct.
		SetCommonErrorResult(&sdk.APIError{}).
		// Handle common exceptions in response middleware.
		OnAfterResponse(func(client *req.Client, resp *req.Response) error {
			if resp.Err != nil { // There is an underlying error, e.g. network error or unmarshal error.
				log.Fatal("response error:", resp.Err)
				return nil
			}
			if apiErr, ok := resp.ErrorResult().(*sdk.APIError); ok {
				log.Println("API error:", apiErr)
				resp.Err = apiErr
				return nil
			}
			// Corner case: neither an error state response nor a success state response,
			// dump content to help troubleshoot.
			if !resp.IsSuccessState() {
				log.Println("response dump:", resp.Dump())
				return fmt.Errorf("bad response, raw dump:\n%s", resp.Dump())
			}
			return nil
		})

	return &XiuXianClient{
		Client: c,
	}
}

// LoginWithToken login with GitHub personal access token.
func (c *XiuXianClient) LoginWithToken(token string) *XiuXianClient {
	c.SetCommonHeader("Authorization", token)
	c.isLogged = true
	return c
}

// IsLogged return true is user is logged in, otherwise false.
func (c *XiuXianClient) IsLogged() bool {
	return c.isLogged
}

// SetDebug enable debug if set to true, disable debug if set to false.
func (c *XiuXianClient) SetDebug(enable bool) *XiuXianClient {
	if enable {
		c.EnableDebugLog()
		c.EnableDumpAll()
	} else {
		c.DisableDebugLog()
		c.DisableDumpAll()
	}
	return c
}
